<template>
  <el-row class="mx__20 px-20 bg-white">
    <el-col class="current-content-style">
      <el-row class="py-20">
        <el-col :span="12" :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form ref="form" :model="customer" :rules="rulesCustomer" label-width="120px">
            <el-form-item label="客户名字" prop="customerName">
              <el-input v-model="customer.customerName" placeholder="请输入客户名称"></el-input>
            </el-form-item>
            <el-form-item label="客户手机号" prop="customerPhone">
              <el-input v-model="customer.customerPhone" placeholder="请输入11位手机号码"></el-input>
            </el-form-item>
            <el-form-item label="客户身份证" prop="customerIdCard">
              <el-input v-model="customer.customerIdCard" placeholder="请输入18位身份证号码"></el-input>
            </el-form-item>
            <el-form-item label="客户类型" prop="customerTypeId">
              <el-select v-model="customer.customerTypeId" placeholder="请选择水表类型">
                <el-option
                  v-for="item in customerTypeList"
                  :key="item.customerTypeId"
                  :label="item.customerTypeName"
                  :value="item.customerTypeId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="客户地址" prop="customerAddress">
              <el-cascader
                style="width: 220px"
                ref="cascader"
                v-model="checkedAddessValues"
                :options="data"
                :props="addressProps"
                clearable
                size="mini"
                separator="-"
                placeholder="请选择"
                :show-all-levels="true"
              ></el-cascader>
              <div>
                <span class="px-20">{{ customer.customerAddress }}</span>
              </div>
            </el-form-item>
            <el-form-item label="客户详细地址" prop="customerAddressInfo">
              <el-input v-model="customer.customerAddressInfo" placeholder="请输入客户详细地址"></el-input>
            </el-form-item>
            <el-form-item label="客户状态" prop="customerState">
              <el-select v-model="customer.customerState" placeholder="请选择客户状态">
                <el-option label="正常" :value="1"></el-option>
                <el-option label="注销" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('form')">添加客户</el-button>
              <el-button type="primary" @click="$router.push('/home/customems')">返回</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script>
// 添加客户
import { getCustomerType, queryRootRegionAll, queryChildrenRegionAll, addCustomer } from '@/config/api'
export default {
  data() {
    return {
      // 三级联动的props配置
      addressProps: {
        expandTrigger: 'click',
        value: 'id', // 多级选择器的option项的value对应数据中的id属性
        label: 'regionName', // 多级选择器的option项的label对应数据中的regionName属性
        lazy: true,
        lazyLoad: this.loadNode
      },
      level_1: [], //存储请求回来的1级地域
      checkedKeys: [], // 选择的地域id
      data: [], //root 地域数组
      checkedAddessValues: [], // 选择的地域名称
      customerTypeList: [],
      customer: {
        customerState: 1,
        customerName: '',
        customerPhone: '',
        customerTypeId: '',
        customerIdCard: '',
        customerAddress: '',
        customerAddressInfo: ''
      },
      rulesCustomer: {
        customerName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        customerPhone: [
          { required: true, message: '请输入客户详细地址', trigger: 'blur' },
          { min: 11, max: 11, message: '长度11个字符', trigger: 'blur' }
        ],
        customerTypeId: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
        customerIdCard: [
          { required: true, message: '请输入客户身份证号码', trigger: 'blur' },
          {
            type: 'string',
            pattern: /(^\d{18}$)|^\d{17}[xX]$/,
            trigger: 'blur',
            message: '身份证应该是18位'
          }
        ],
        customerAddress: [{ required: true, message: '请选择客户主要地址', trigger: 'blur' }],
        customerAddressInfo: [{ required: true, message: '请输入客户详细地址', trigger: 'blur' }]
      }
    }
  },
  watch: {
    checkedAddessValues(val) {
      console.log('checkedAddessValues', val) // [52,54,55]
      this.checkedKeys = val
      // 获取到选择的节点数组对象
      let arr = this.$refs.cascader.getCheckedNodes()
      // 拿到数组里面的所有三级联动的节点数组
      let pathNodes = arr[0].pathNodes

      // 获取中文地名
      let add = []
      pathNodes.forEach(el => {
        add.push(el.label)
      })
      // console.log(add)
      // 赋值中文地名给属性变量
      this.customer.customerAddress = add.join('-')
    },
    level_1(val) {
      // console.log(val)
      let regionArr = []
      let idArr = []
      val.forEach(el => {
        // 这个对象的属性，和defaultProps的配置有关联，label对应的值，要是这个对象里面的地名的属性
        // level属性，用来判断是几级地域
        let obj = { id: el.regionId, regionName: el.regionName, level: 1 }
        regionArr.push(obj)
        idArr.push(el.regionId)
      })
      this.data = regionArr
      this.defaultExpandedKeys = idArr
    }
  },
  methods: {
    // 添加客户
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.customer)
          let params = {
            // address: this.checkedKeys[this.checkedKeys.length - 1], //【1，2，14】z最后一个ID
            // addressInfo: this.customer.customerAddressInfo,
            // phone: this.customer.customerPhone,
            // changeInfo: this.customer.changeInfo,
            // state: this.customer.customerState,
            // customerId: this.customer.customerId,
            // customerTypeId: this.customer.customerTypeId
            ...this.customer,
            customerAddress: this.checkedKeys[this.checkedKeys.length - 1]
          }
          addCustomer(params)
            .then(res => {
              console.log(res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '添加客户信息成功'
                })
                this.$router.push('/home/customems')
              } else {
                this.$message({
                  type: 'error',
                  message: '添加客户信息失败'
                })
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          return false
        }
      })
    },
    // 获取客户类型
    getCustomerTypeList() {
      getCustomerType().then(res => {
        if (res.code === 200) {
          // console.log(res)
          this.customerTypeList = res.data
        } else {
          this.$message({
            type: 'error',
            message: '查询客户类型数据失败'
          })
        }
      })
    },
    // 获取一个节点的子级
    getChildReginHandler(id) {
      return queryChildrenRegionAll({ regionParentId: id }).then(res => {
        // console.log(res)
        if (res.code === 200) {
          return res.data
        }
      })
    },
    // 动态加载子tree
    loadNode(node, resolve) {
      console.log(node, resolve)
      if (node.root) return
      this.getChildReginHandler(node.data.id).then(res => {
        // console.log(res)
        let level = node.data.level + 1
        let regionArr = []
        let leaf = false
        level === 3 && (leaf = true)
        res.forEach(el => {
          let obj = { id: el.regionId, regionName: el.regionName, level, leaf }
          regionArr.push(obj)
        })
        // console.log(regionArr)
        resolve(regionArr)
      })
    },
    /*  // 选择1、2级别的地域时触发
    handleCheck(vlue) {
      console.log(vlue) // [6,7]
    },
    // 选中或清除选择的地域时触发的事件函数
    handleChange(value) {
      console.log(value) // 返回：[1,2,14]
    }, */
    // 查询所有根地域
    queryRootRegionAllHandler() {
      queryRootRegionAll().then(res => {
        if (res.code === 200) {
          console.log(res)
          this.level_1 = res.data
        } else {
          this.$message({
            message: '查询根地域失败',
            type: 'error'
          })
        }
      })
    }
  },
  created() {
    this.getCustomerTypeList()
    this.queryRootRegionAllHandler()
  }
}
</script>

<style scoped>
.el-input {
  width: 250px;
}
</style>
